package com.lancoo.answer.widget.combinationView;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.ivan.EasyImageSelect;
import com.ivan.GlideEngine;
import com.ivan.easyphotos.EasyPhotos;
import com.ivan.easyphotos.constant.CaptureEvent;
import com.ivan.easyphotos.models.album.entity.Photo;
import com.lancoo.answer.R;
import com.lancoo.answer.helper.ConfirmDialogHelper;
import com.lancoo.answer.helper.PictureRecognitionHelper;
import com.lancoo.answer.model.ConstantBean;
import com.lancoo.answer.model.bean.Item;
import com.lancoo.answer.model.entity.TaskControlBean;
import com.lancoo.answer.util.EditTextInputUtil;
import com.lancoo.answer.util.ExamFontSizeAdjustUtils;
import com.lancoo.answer.util.SoftInputUtils;
import com.lancoo.answer.view.fragment.composition.adapter.ImageAdapter;
import com.rxjava.rxlife.RxLife;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by pengmi on 2022/7/8 17:06
 * Description:图片作答组合view
 */
public class PictureAnswerView extends LinearLayout implements View.OnClickListener{
    
    private String typeNo;
    private Item item;
    private ImageAdapter mAdapter;
    private List<String> showImgList;
    private long subTime;
    private PictureAnswerCallBack callBack;
    private int maxSize=3;
    private int typeIndex,quesIndex,childIndex,itemIndex;


    public PictureAnswerView(Context context) {
        super(context);
        initView();
    }

    public PictureAnswerView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public PictureAnswerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView(){
        Context context=getContext();
        LayoutInflater.from(context).inflate(R.layout.ev_layout_picture_answer_view,this);
        showImgList=new ArrayList<>();
        adjustFontSize();
    }

    public void setIndex(int typeIndex,int quesIndex,int childIndex,int itemIndex){
        this.typeIndex=typeIndex;
        this.quesIndex=quesIndex;
        this.childIndex=childIndex;
        this.itemIndex=itemIndex;
    }


    public void setCallBack(PictureAnswerCallBack callBack){
        this.callBack=callBack;
    }

    public void setMaxSize(int maxSize){
        this.maxSize=maxSize;
    }
    
    public void initData(Item item, String typeNo){
        this.item=item;
        this.typeNo=typeNo;
        updateRecognitionStyle(false);

        EditText edittext = findViewById(R.id.edittext);
        if(TextUtils.isEmpty(item.getImgRecognitionTxt())){
            item.setImgRecognitionTxt("");
        }
        edittext.setText(item.getImgRecognitionTxt());
        edittext.setSelection(edittext.getText().length());
        findViewById(R.id.tv_clear_txt).setOnClickListener(this);
        EditTextInputUtil.disableCopyAndPaste(edittext);
        SoftInputUtils.setEditTextInputSpace(edittext);
        edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                updateAnswerContent(s.toString().trim());
                edittext.requestLayout();
                updateAnswerCount();
            }
        });
        RecyclerView mRecyclerView = findViewById(R.id.recyclerView);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext(),
                LinearLayoutManager.HORIZONTAL,false));
        List<String> imagePath = item.getImagePathList();
        if(imagePath==null||imagePath.size()==0||imagePath.get(0)==null){
            List<String> list=new ArrayList<>();
            item.setImagePathList(list);
        }else{
            showImgList.addAll(item.getImagePathList());
        }
        mAdapter = new ImageAdapter(showImgList,0);
        mAdapter.setMaxSize(maxSize);
        mAdapter.setImageOperateCallBack(new ImageAdapter.ImageOperateCallBack() {

            @Override
            public void gotoImageLibChoice() {
                TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
                int trainSence = taskControlBean.getTrainSence();
                if(trainSence!=0){
                    showPictureChoiceDialog();
                }else{
                    startImageViewChoice();
                }
            }

            @SuppressLint("NotifyDataSetChanged")
            @Override
            public void deletChoiceImage(int position){
                showImgList.remove(position);
                if(mAdapter !=null){
                    mAdapter.notifyDataSetChanged();
                }
                item.setImagePathList(showImgList);
                updateRecognitionStyle(false);
                onDeletImgCallBack(position);
            }

            @Override
            public void lookChoiceImage(int position){
                EasyPhotos.startPreviewPaths((FragmentActivity) getContext(), GlideEngine.getInstance(),
                        showImgList,true,position);
            }

        });
        mRecyclerView.setAdapter(mAdapter);
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        findViewById(R.id.ll_txt).setVisibility(taskControlBean!=null&&taskControlBean.isCloseMediaAnswer()?GONE:VISIBLE);
    }



    /**
     * 识别内容有修改，界面样式有更新
     */
    public void updateRecognitionStyle(boolean isShow){
        findViewById(R.id.recyclerView).setVisibility(isShow?View.GONE:View.VISIBLE);
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        TextView tv_alert = findViewById(R.id.tv_picture_answer_alert);
        boolean isEmptyAnswer=showImgList == null || showImgList.size() <= 0;
        if(!TextUtils.isEmpty(item.getImgRecognitionTxt())){
            isEmptyAnswer=false;
        }
        if(taskControlBean!=null&&taskControlBean.getTrainSence()==0){
            tv_alert.setText(R.string.ev_ai_exame_picture_anwer_practice_alert);
            TextView tv_alertPaper = findViewById(R.id.tv_paper_answer_alert);
            tv_alertPaper.setText(R.string.ev_exame_submit_answer_txt_alert);

        }
        if(isEmptyAnswer){
            findViewById(R.id.tv_picture_answer_alert).setVisibility(View.VISIBLE);
            findViewById(R.id.tv_answer_count).setVisibility(View.GONE);
            findViewById(R.id.edittext).setVisibility(View.GONE);
            findViewById(R.id.ll_clear_txt).setVisibility(View.GONE);
            findViewById(R.id.view_12dp).setVisibility(View.GONE);
        }else{
            findViewById(R.id.tv_picture_answer_alert).setVisibility(View.GONE);
            findViewById(R.id.tv_answer_count).setVisibility(View.VISIBLE);
            findViewById(R.id.edittext).setVisibility(View.VISIBLE);
//            findViewById(R.id.ll_edittext).setVisibility(View.VISIBLE);
            findViewById(R.id.ll_clear_txt).setVisibility(View.VISIBLE);
            findViewById(R.id.view_12dp).setVisibility(View.VISIBLE);
            if(!TextUtils.equals("W",typeNo)){
                //如果不是听写题，后续不用处理
                return;
            }
            findViewById(R.id.tv_answer_count).setVisibility(View.GONE);
            findViewById(R.id.ll_clear_txt).setVisibility(View.GONE);
            findViewById(R.id.edittext).setBackgroundResource(R.drawable.ev_shape_3_corners_f7_bg);
        }
    }




    /**
     * 进入图片选择器
     */
    private void startImageViewChoice(){
        long onClickSubTime = ConstantBean.Companion.getOnClickSubTime();
        if(System.currentTimeMillis()-onClickSubTime<500){
           return;
        }
        ConstantBean.Companion.setOnClickSubTime(System.currentTimeMillis());
        TaskControlBean taskControlBean = ConstantBean.Companion.getTaskControlBean();
        if(taskControlBean==null){
            return;
        }
         EasyImageSelect.withImage((FragmentActivity) getContext())
                .setNeedCompress(true)
                .setNeedRecognite(!taskControlBean.isCloseMediaAnswer())
                .setUseCustomCamera(true)
                .setIsfilpCamera(false)
                .setOnlyCapture(true)
                .setMaxImageNumber(maxSize - showImgList.size())
                .setRecognitionEngine((context, photos, callback) ->
                        PictureRecognitionHelper.startPictureRecognition(context, photos, callback, item))
                .setCallBack(new EasyImageSelect.ImageSelectCallBack() {
                    @Override
                    public void onImageSelectResult(List<String> imgList, List<Photo> photos) {
                        Log.e("choice img", "获取图片回来");
                        onImgsUploadCallBack(imgList);
                        updateRecognitionStyle(false);
                        updateRecognitionContent();
//                        if(trainSence!=0){
//
//                        }
                    }

                    @Override
                    public void onDismiss() {

                    }
                }).show();
    }


    /**
     * 统计作答个数
     */
    private void updateAnswerCount(){
        TextView tv_answerCount=findViewById(R.id.tv_answer_count);

        Observable.create((ObservableOnSubscribe<Integer>) emitter -> {
                    int count=0;
                    if(!TextUtils.isEmpty(item.getImgRecognitionTxt())){
                        String[] split = item.getImgRecognitionTxt()
                                .replace("\n"," ")
                                .split(" ");
                        count=split.length;
                        for (String str : split) {
                            if (str.isEmpty()) {
                                count--;
                            }
                        }
                    }
                    emitter.onNext(Math.max(count,0));
                })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .as(RxLife.as(this,true))
                .subscribe(integer -> {

                    SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
                    spannableStringBuilder.append("Word Count:");
                    SpannableString spannableString=new SpannableString(""+integer);
                    spannableString.setSpan(new ForegroundColorSpan(0xff666666),0,spannableString.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    spannableStringBuilder.append(spannableString);
                    tv_answerCount.setText(spannableStringBuilder);
                }, throwable -> {});
    }


    /**
     *更新识别内容
     */
    private void updateRecognitionContent(){
        EditText edittext = findViewById(R.id.edittext);
        edittext.setText(item.getImgRecognitionTxt());
        edittext.setSelection(edittext.getText().length());
        edittext.requestLayout();
    }


    /**
     *  清空文本确认弹窗
     */
    private void showClearTxtConfigDialog(){
        ConfirmDialogHelper.showConfirmDialog(getContext(), 1, "温馨提示",
                "您确认清空文本吗？", "确定", "取消", new ConfirmDialogHelper.ConfirCallBack() {
                    @Override
                    public void onSure() {
                        super.onSure();
                        item.setImgRecognitionTxt("");
                        updateRecognitionContent();
                        updateAnswerCount();
                        updateRecognitionStyle(false);
                        if(getContext()==null){
                            return;
                        }
                        SoftInputUtils.hideSoftInput((Activity) getContext());
                    }
                });

    }

    @SuppressLint("NotifyDataSetChanged")
    public void updateImgAdapterData(){
        if(mAdapter!=null){

            List<String> imagePathList = item.getImagePathList();
            if(imagePathList==null){
                return;
            }
            List<String> temp = new ArrayList<>(imagePathList);
            showImgList.clear();
            showImgList.addAll(temp);
            item.setImagePathList(temp);
            mAdapter.notifyDataSetChanged();
            updateRecognitionStyle(false);
        }
    }

    @Override
    public void onClick(View v) {
        if(System.currentTimeMillis()-subTime<500){
            return;
        }
        subTime=System.currentTimeMillis();
        int id=v.getId();
        if(id==R.id.tv_clear_txt){
            showClearTxtConfigDialog();
        }
    }

    /**
     * 更新作答内容
     * @param content 修改识别内容
     */
    private void updateAnswerContent(String content){
        item.setImgRecognitionTxt(content);
        if(callBack!=null){
            callBack.onImgTxtUpdate(content);
        }
    }

    /**
     * 图片删除处理
     */
    private void onDeletImgCallBack(int position){
        Log.e("imgO","onDeletImgCallBack"+position);
        if(callBack!=null){
            callBack.onDeletCallBack(position);
        }
    }

    /**
     * 图片批量上传处理
     */
    private void onImgsUploadCallBack(List<String> imgs){
        if(callBack!=null){
            callBack.onImgListUpLoad(imgs);
        }
    }



    public interface PictureAnswerCallBack{

        void onDeletCallBack(int position);

        void onImgListUpLoad(List<String> imgs);

        void onImgTxtUpdate(String content);

    }

    public void adjustFontSize(){
        TextView textView = findViewById(R.id.tv_picture_answer_alert);
        TextView textView1 = findViewById(R.id.tv_answer_count);
        TextView textView2 = findViewById(R.id.edittext);
        TextView textView3 = findViewById(R.id.tv_paper_answer_alert);
        TextView textView4 = findViewById(R.id.tv_clear_txt);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView,14);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView1,13);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView2,13);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView3,13);
        ExamFontSizeAdjustUtils.adjustTextViewFontSize(textView4,13);

    }

    private void showPictureChoiceDialog(){
        AlertDialog mDialog = new AlertDialog.Builder(getContext()).create();
        Window window = mDialog.getWindow();
        window.setBackgroundDrawableResource(android.R.color.white);  //解决5.0以上手机dialog无法横向占满屏幕的问题
        window.getAttributes().gravity = Gravity.BOTTOM;
        window.getDecorView().setBackgroundColor(Color.TRANSPARENT);
        LayoutInflater inflater = LayoutInflater.from(getContext());
        View contentView = inflater.inflate(R.layout.easy_image_select, null);
        contentView.findViewById(R.id.selectBtn).setVisibility(View.GONE);
        contentView.findViewById(R.id.cameraBtn).setBackgroundResource(R.drawable.easy_shape_image_bg_4);
        contentView.findViewById(R.id.line1).setVisibility(View.GONE);
        contentView.findViewById(R.id.cameraBtn).setOnClickListener(view -> {
            mDialog.dismiss();
            CaptureEvent captureEvent=new CaptureEvent();
            captureEvent.setTypeIndex(typeIndex);
            captureEvent.setQuesIndex(quesIndex);
            captureEvent.setChildIndex(childIndex);
            captureEvent.setItemIndex(itemIndex);
            captureEvent.setItemIndexInPaper(item.getItemIndex());
            Log.e("eee","考试进来了:"+new Gson().toJson(captureEvent));
            EventBus.getDefault().post(captureEvent);
        });
        contentView.findViewById(R.id.cancelBtn).setOnClickListener(view -> mDialog.dismiss());
        mDialog.show();
        mDialog.setContentView(contentView);
    }

    public void updateImgAnswerCallBack(List<String> imgList){
        onImgsUploadCallBack(imgList);
        updateRecognitionStyle(false);
        updateRecognitionContent();
    }

}
